import { createStore } from 'vuex'
import { getLyric } from '@/network/recommendSongList/songListDetail.js'
import { phoneLogin, userDetail } from '@/network/profile/user.js'
import { Toast } from 'vant'

export default createStore({
  state: {
    // 初始化数据
    playlist: [{
      name: 'xxx',
      id: '1908983687',
      al: {
        id: 412388,
        name: "Popular Traditional Music",
        pic: 2432119720658500,
        picUrl: "http://p3.music.126.net/hBHb9pzG50vFrlT8SZCd3Q==/2432119720658500.jpg"
      },
      ar: [
        {id: 33913095, name: 'KIND', tns: Array(0), alias: Array(0)}
      ]
    }],
    // 当前播放第几首
    playCurrentIndex: 0,
    // 控制播放和暂停图标的显示和隐藏，当切换歌曲或歌单时，都要重置为 true（显示播放图标）
    // 为 true时，显示播放图标，为 false时，显示暂停图标
    toggle: true,
    // 歌词
    lyric: '',
    // 歌词时间
    currentTime: 0,
    intervalId: 0,
    // 用户信息
    user: {
      isLogin: false,
      account: {},
      userDetail: {}
    }
  

  }, 
  mutations: {
    // 修改歌单列表
    setPlaylist: (state, value) => {
      state.playlist = value
      // state.toggle = true
      // 每个歌单列表的第一条歌曲信息
      // console.log(state.playlist[state.playCurrentIndex].al.id);
    },
    // 追加歌单列表
    pushPlaylist: (state, value) => {
      // console.log(value);
      // 将搜索出来的歌曲图片和歌名同步
      value.al.name = value.name
      value.al.picUrl = value.album.artist.img1v1Url
      state.playlist.push(value)

      // console.log(state.searchMusicList);
    },
    // 通过索引改变歌曲
    playCurrentIndex: (state, index) => {
      state.playCurrentIndex = index
      state.toggle = false
    },
    // 修改歌曲
    setLyric: (state, value) => {
      state.lyric = value
    },
    // 更新时间
    setCurrentTime: (state, value) => {
      state.currentTime = value
    },
    // 修改用户登录状态
    setUser: (state, value) => {
      state.user = value
    }
  },
  actions: {
    // 请求歌词数据
    async reqLyric(content, payload) {
      // console.log(payload);
      const { data: res } = await getLyric(payload.id)
      content.commit('setLyric', res.lrc.lyric)
      // console.log(res.lrc.lyric);
    },
    // 登录
    async loginByPhone(content, payload) {
      // console.log(payload);
      try {
        const { data: res } = await phoneLogin(payload.phone, payload.password)
        console.log(res);
        if (res.code === 400) {
          Toast.fail('手机号码格式错误')
        } else if (res.code === 502) {
          Toast.fail('密码错误');
        } else if (res.code === 200) {
          Toast.success('登陆成功')
          content.state.user.isLogin = true
          content.state.user.account = res.account
          
          // 请求用户详情，并保存至用户状态中
          const { data: userRes } = await userDetail(res.account.id)
          content.state.user.userDetail = userRes
          // 保存至本地
          localStorage.userData = JSON.stringify(content.state.user)
          content.commit('setUser', content.state.user)
          return res
        }
      } catch (err) {
        Toast.fail('密码错误超过限制，请稍后再登录')
      }
      
    }
    
  },
  getters: {
    // 格式化歌词数据
    lyricList: (state) => {

      let arr = state.lyric.split(/\n/igs).map((item, i, arr) => {
        let min = parseInt(item.slice(1, 3))      // 分
        let sec = parseInt(item.slice(4, 6))     // 秒
        let mill = parseInt(item.slice(7, 10).replace(']', ''))  // 毫秒
  
        return {
          min,
          sec,
          mill,
          lyric: item.slice(10, item.length).replace(']', ''),
          content: item,
          time: mill + sec * 1000 + min * 60 * 1000
        }
      })

      arr.forEach((item, i) => {
        if (i <= 0) { 
          item.pre = 0
        } else {
          item.pre = arr[i-1].time
        }
      })

      // console.log(arr);
      return arr
    }
  },
  modules: {
  }
})
